package com.yhcnet.controller;

import com.google.code.kaptcha.Producer;
import com.yhcnet.po.Result;
import com.yhcnet.utils.RedisUtils;
import org.apache.ibatis.util.MapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@CrossOrigin
@RequestMapping("/code")
public class CodeController {
    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private Producer producer;

    public final String CAPTCHA_KEY = "captcha";

    /**
     * 获取验证码以及验证码id
     * @return
     */
    @RequestMapping("/captcha")
    public Result getCode() throws IOException {
        //验证码key
        String key = UUID.randomUUID().toString();
        //随机验证码
        String code = producer.createText();
        // 生成图片
        BufferedImage image = producer.createImage(code);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image,"jpg",outputStream);

        BASE64Encoder encoder = new BASE64Encoder();
        // 前缀
        String str_font = "data:img/jepg;base64,";

        String base64Img = str_font + encoder.encode(outputStream.toByteArray());

        // 存在 redis 中
        redisUtils.hset(CAPTCHA_KEY,key,code,300);

        return Result.succ(new Image(key,base64Img));
    }

    public class Image {
        String key ;
        String base64Img;

        public Image() {
        }

        public Image(String key, String base64Img) {
            this.key = key;
            this.base64Img = base64Img;
        }

        public String getKey() {
            return key;
        }

        public void setKey(String key) {
            this.key = key;
        }

        public String getBase64Img() {
            return base64Img;
        }

        public void setBase64Img(String base64Img) {
            this.base64Img = base64Img;
        }
    }

}
